<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Notification;
use App\Notifications\ForgetPassword as f;
class ForgetPassword extends Controller
{
    //
    public function writeEmail(){
        //echo '输入邮箱地址';
        //加载输入邮箱地址模板
        return view('forgetPassword.writeEmaill');
    }

    public function sendEmail(Request $request){
        //获取post数据中的email
        $post = $request->all();
        //dd($post);
        //找到用户表中email等于post数据中的email的数据中
        $user = User::where('email', $post['email'])->first();
        if($user){
            //如果能找到用户数据才能发送邮件
            //第一个参数是通知消息发送给的用户数据对象,该数据对象中一定要有email字段
            //第二个参数是发送的消息通知类
            Notification::send($user,new f($user['email']));
            //如果发送成功设置发送成功的闪存提示并加载页面
            session()->flash('success','邮件已发送！请前往邮箱进行操作！');
            return view('forgetPassword.sendOk');
        }
    }

    //加载修改密码模板
    public function changePassword($email){
        //echo '我是改密码的';
        return view('forgetPassword.password',compact('email'));
    }

    //处理修改密码模板
    public function change(Request $request){
        //接受post用户数据
        $post = $request->all();
        $validator = $request->validate(
            [
                'password' => 'required|between:6,16|confirmed',
                'password_confirmation' => 'required|between:6,16',
            ]
        );
        //dd($validator);
        //只有通过要争才能进行下面的修改密码操作
        $user = User::where('email', $post['email'])->first();
        $user->password = bcrypt($post['password']);
        $user->save();
        //设置闪存信息并返回
        session()->flash('success','密码修改成功,请登录!!');
        return redirect()->route('login');
    }

}
